import 'package:baseproject/model/status/status.dart';
import 'package:baseproject/network/httpUtil.dart';
import 'package:baseproject/view/base/basePage.dart';
import 'package:baseproject/view/index/textWidget.dart';
import 'package:flutter/material.dart';

class Index extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _IndexState();
  }
}

class _IndexState extends State<Index> {
  // 服务器状态组件
  GlobalKey<TextWidgetState> textWeightKey = GlobalKey();

  @override
  void initState() {
    super.initState();
    // addPostFrameCallback回调方法在Widget渲染完成时触发，所以一般我们在获取页面中的Widget大小、位置时使用到。
    WidgetsBinding.instance.addPostFrameCallback((_) {
      /// 接口请求
      getServerStatus();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Container(
      alignment: Alignment.center,
      decoration: BoxDecoration(
          image: DecorationImage(
              image: AssetImage("images/home_bg.jpg"), fit: BoxFit.cover)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          TextWidget(textWeightKey),
          OutlineButton(
            onPressed: () {
              Navigator.of(context).push(new MaterialPageRoute(
                  builder: (context) {
                    return new BasePage();
                  },
                  fullscreenDialog: true));
            },
            child: Text("跃迁引擎启动",
                style: TextStyle(fontSize: 18.0, color: Colors.white)),
          )
        ],
      ),
    ));
  }

  @override
  void deactivate() {
    super.deactivate();
    var bool = ModalRoute.of(context).isCurrent;
    if (bool) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        /// 接口请求
        getServerStatus();
      });
    }
  }

  // 获取服务器状态
  getServerStatus() async {
    var _serviceStatus = "loading...";
    Status status;
    await HttpUtil().get("/latest/status",
        data: {"datasource": "serenity"}, showLoading: false, success: (data) {
      status = new Status.fromJson(data);
    });
    if (null != status) {
      var vip = status.vip != null ? "[VIP]" : "";
      _serviceStatus = "晨曦" + vip + "- 在线（${status.players}玩家）";
    } else {
      _serviceStatus = "服务器离线";
    }
    textWeightKey.currentState.changeText(_serviceStatus);
  }
}
